﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;

namespace KFS_Inventory_CigInput
{
    public partial class login : Form
    {
        int loginCounter = 0;
        public login()
        {
            InitializeComponent();

        }

        private void loginButton_Click(object sender, EventArgs e)
        {
            string username = userBox.Text;
            string password = pwBox.Text;
            string store = comboBox1.Text;

            // Connect to the database
            var mongoConnect = "mongodb://root:b713eb8b@ds029811.mongolab.com:29811/kreiser_inventory";
            MongoClient client = new MongoClient(mongoConnect);
            MongoServer server = client.GetServer();
            MongoDatabase kfs_inv = server.GetDatabase("kreiser_inventory");
            var userCollection = kfs_inv.GetCollection<BsonDocument>("UserInfo"); // Connect to "UserInfo" collection
            var userQuery = Query.EQ("username", username);
            foreach (BsonDocument userInfo in userCollection.Find(userQuery))
            {
                if (userInfo["password"].ToString() == password)
                {

                    if (userInfo["storeAccess"].ToString() == store)
                    {
                        // Authenticated, build user interface
                        MessageBox.Show("You have successfully connected to KFS_Inventory.");
                        loginCounter = 0;
                        userBox.Text = "";
                        pwBox.Text = "";
                        comboBox1.Text = "";
                        dataEntry dataForm = new dataEntry(store, username);
                        dataForm.Show();

                    }

                    else
                    {
                        MessageBox.Show("You are now allowed to access this store.");
                        loginCounter++;
                        if (loginCounter > 4)
                        {
                            this.Close();
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Your username or password is incorrect.");
                    loginCounter++;
                    if (loginCounter > 4)
                    {
                        this.Close();
                    }
                }
            }
        }

        private void createButton_Click(object sender, EventArgs e)
        {
            createAccount accountForm = new createAccount();
            accountForm.Show();
        }
    }
}
